<template>
  <a-form
    :model="formState"
    :rules="rules"
    v-bind="layout"
    name="nest-messages"
    @finish="onFinish"
    @finishFailed="onFinishFailed"
  >
    <a-form-item name="scenicName" label="景点名称" :rules="rules.scenicName">
      <a-input v-model:value="formState.scenicName" placeholder="请输入景点名称" />
    </a-form-item>
    <a-form-item name="scenicBrief" label="景点简介" :rules="rules.scenicBrief">
      <a-textarea v-model:value="formState.scenicBrief" placeholder="请输入景点简介" />
    </a-form-item>
    <a-form-item name="tags" label="景点标签">
      <a-select
        v-model:value="formState.tags"
        mode="multiple"
        placeholder="请选择标签"
        style="width: 100%"
      >
        <a-select-option
          v-for="scenicTag in scenicTags"
          :key="scenicTag.id"
          :value="scenicTag.tagName"
        >
          {{ scenicTag.tagName }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item name="tips" label="景点建议">
      <a-input v-model:value="formState.tips" placeholder="请输入景点建议" />
    </a-form-item>
    <a-form-item name="scenicLongitude" label="景点经度" :rules="rules.scenicLongitude">
      <a-input-number
        v-model:value="formState.scenicLongitude"
        placeholder="请输入经度"
        :precision="6"
        style="width: 100%"
      />
    </a-form-item>
    <a-form-item name="scenicLatitude" label="景点纬度" :rules="rules.scenicLatitude">
      <a-input-number
        v-model:value="formState.scenicLatitude"
        placeholder="请输入纬度"
        :precision="6"
        style="width: 100%"
      />
    </a-form-item>
    <a-form-item name="coverImage" label="封面图片" :rules="rules.coverImage">
      <a-upload
        v-model:file-list="coverImageList"
        :before-upload="beforeUpload"
        max-count="1"
        list-type="picture-card"
        accept="image/*"
        @change="handleCoverImageChange"
      >
        <div v-if="coverImageList.length < 1">
          <PlusOutlined />
          <div style="margin-top: 8px">上传封面图片</div>
        </div>
      </a-upload>
    </a-form-item>
    <a-form-item name="scenicImages" label="景点图片">
      <a-upload
        v-model:file-list="scenicImageList"
        :before-upload="beforeUpload"
        list-type="picture-card"
        accept="image/*"
        @change="handleScenicImagesChange"
      >
        <div>
          <PlusOutlined />
          <div style="margin-top: 8px">上传景点图片</div>
        </div>
      </a-upload>
    </a-form-item>
    <a-form-item :wrapper-col="{ ...layout.wrapperCol, offset: 8 }">
      <a-button type="primary" html-type="submit" :loading="loading">
        {{ loading ? '提交中...' : '提交' }}
      </a-button>
      <a-button style="margin-left: 10px" @click="resetForm">重置</a-button>
      <a-button style="margin-left: 10px" @click="handleCancel">取消</a-button>
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { addScenic } from '@/api/scenicController'
import { listTag } from '@/api/tagController'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import type { UploadChangeParam, UploadFile } from 'ant-design-vue'

// 定义 emit 事件
const emit = defineEmits<{
  success: []
  cancel: []
}>()

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
}

// 表单验证规则
const rules = {
  scenicName: [
    { required: true, message: '请输入景点名称', trigger: 'blur' },
    { min: 2, max: 50, message: '景点名称长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  scenicBrief: [
    { required: true, message: '请输入景点简介', trigger: 'blur' },
    { min: 10, max: 500, message: '景点简介长度在 10 到 500 个字符', trigger: 'blur' },
  ],
  scenicLongitude: [
    { required: true, message: '请输入景点经度', trigger: 'blur' },
    {
      type: 'number',
      min: -180,
      max: 180,
      message: '经度必须在 -180 到 180 之间',
      trigger: 'blur',
    },
  ],
  scenicLatitude: [
    { required: true, message: '请输入景点纬度', trigger: 'blur' },
    { type: 'number', min: -90, max: 90, message: '纬度必须在 -90 到 90 之间', trigger: 'blur' },
  ],
  coverImage: [{ required: true, message: '请上传封面图片', trigger: 'change' }],
}

const loading = ref(false)
const coverImageList = ref<UploadFile[]>([])
const scenicImageList = ref<UploadFile[]>([])

const formState = reactive<API.addScenicParams>({
  scenicName: '',
  scenicBrief: '',
  tags: [],
  tips: '',
  scenicLongitude: undefined,
  scenicLatitude: undefined,
  coverImage: undefined,
  scenicImages: [],
})

// 文件上传前的验证
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }

  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    message.error('图片大小不能超过 5MB!')
    return false
  }

  return false // 阻止自动上传，手动处理
}

// 处理封面图片变化
const handleCoverImageChange = (info: UploadChangeParam) => {
  coverImageList.value = [...info.fileList]
  if (info.fileList.length > 0) {
    const file = info.fileList[0]
    if (file.originFileObj) {
      formState.coverImage = file.originFileObj
    }
  } else {
    formState.coverImage = undefined
  }
}

// 处理景点图片变化
const handleScenicImagesChange = (info: UploadChangeParam) => {
  scenicImageList.value = [...info.fileList]
  formState.scenicImages = info.fileList
    .filter((file) => file.originFileObj)
    .map((file) => file.originFileObj!) as File[]
}

// 表单提交成功
const onFinish = async (values: typeof formState) => {
  console.log('=== 表单提交调试信息 ===')
  console.log('1. onFinish 接收到的 values:', JSON.stringify(values, null, 2))
  console.log('2. 当前 formState 状态:', JSON.stringify(formState, null, 2))
  console.log('3. 景点名称检查:')
  console.log('   - values.scenicName:', `"${values.scenicName}"`)
  console.log('   - formState.scenicName:', `"${formState.scenicName}"`)
  console.log('=========================')

  loading.value = true

  try {
    const formData = new FormData()

    // 确保使用有效的数据源
    const scenicName = values.scenicName || formState.scenicName
    const scenicBrief = values.scenicBrief || formState.scenicBrief
    const tags = values.tags || formState.tags || []
    const tips = values.tips || formState.tips
    const scenicLongitude = values.scenicLongitude ?? formState.scenicLongitude ?? 0
    const scenicLatitude = values.scenicLatitude ?? formState.scenicLatitude ?? 0

    // 验证关键字段
    if (!scenicName || scenicName.trim() === '') {
      message.error('景点名称不能为空！')
      loading.value = false
      return
    }

    if (!scenicBrief || scenicBrief.trim() === '') {
      message.error('景点简介不能为空！')
      loading.value = false
      return
    }

    console.log('=== 准备发送的数据 ===')
    console.log('scenicName:', `"${scenicName}"`)
    console.log('scenicBrief:', `"${scenicBrief}"`)
    console.log('tags (数组):', tags)
    console.log('tags (转换为字符串):', tags.join(','))
    console.log('tips:', `"${tips}"`)
    console.log('经纬度:', { scenicLongitude, scenicLatitude })

    // 添加基本字段到 FormData
    formData.append('scenicName', scenicName.trim())
    formData.append('scenicBrief', scenicBrief.trim())
    // 将标签数组转换为逗号分隔的字符串
    formData.append('tags', tags.join(','))
    formData.append('tips', tips || '')
    formData.append('scenicLongitude', scenicLongitude.toString())
    formData.append('scenicLatitude', scenicLatitude.toString())

    // 添加封面图片
    if (formState.coverImage) {
      formData.append('coverImage', formState.coverImage)
      console.log('添加封面图片:', formState.coverImage.name)
    } else {
      console.log('警告: 没有封面图片')
    }

    // 添加景点图片
    if (formState.scenicImages && formState.scenicImages.length > 0) {
      formState.scenicImages.forEach((image: File, index: number) => {
        formData.append('scenicImages', image)
        console.log(`添加景点图片 ${index + 1}:`, image.name)
      })
    } else {
      console.log('没有景点图片')
    }

    // 打印最终的 FormData 内容
    console.log('=== FormData 最终内容 ===')
    for (const [key, value] of formData.entries()) {
      if (value instanceof File) {
        console.log(`${key}: [文件] ${value.name} (${value.size} bytes)`)
      } else {
        console.log(`${key}: "${value}"`)
      }
    }
    console.log('=========================')

    const res = await addScenic(formData)
    console.log('=== 服务器响应 ===')
    console.log('响应数据:', res)

    const responseData = res as { data: API.BaseResponseLong }
    if (responseData.data?.code === 200 && responseData.data?.data) {
      message.success('景点添加成功！')
      resetForm()
      // 触发成功事件，通知父组件刷新数据
      emit('success')
    } else {
      console.log('添加失败，服务器返回:', responseData.data)
      message.error('添加失败：' + (responseData.data?.message || '未知错误'))
    }
  } catch (error) {
    console.error('提交失败:', error)
    message.error('提交失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 表单提交失败
const onFinishFailed = (errorInfo: {
  errorFields: Array<{ name: string[]; errors: string[] }>
}) => {
  console.log('Failed:', errorInfo)
  message.error('请检查表单填写是否正确')
}

// 重置表单
const resetForm = () => {
  formState.scenicName = ''
  formState.scenicBrief = ''
  formState.tags = []
  formState.tips = ''
  formState.scenicLongitude = undefined
  formState.scenicLatitude = undefined
  formState.coverImage = undefined
  formState.scenicImages = []
  coverImageList.value = []
  scenicImageList.value = []
}

// 取消表单
const handleCancel = () => {
  resetForm()
  emit('cancel')
}

const scenicTags = ref<API.TagVO[]>([])

// 获取标签数据
const getTagList = async () => {
  try {
    const res = await listTag({})
    const responseData = res as { data: API.BaseResponseListTagVO }
    if (responseData.data?.code === 200 && responseData.data?.data) {
      scenicTags.value = responseData.data.data ?? []
    } else {
      message.error('获取标签失败：' + (responseData.data?.message || '未知错误'))
    }
  } catch (error) {
    console.error('获取标签失败:', error)
    message.error('获取标签失败，请稍后再试')
  }
}

// 初始化获取标签
getTagList()
</script>
